const re = require('../../utils/request.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    info: {
      id: 1,
      itemName: "",
      content: "",
      moduleName: "",
      moduleId: 1
    },
    fileList: [],
    score: 1,
    reason: ""
  },
  afterRead(event) {
    const { file } = event.detail;
    const { fileList = [] } = this.data;
    const thisPtr = this
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: re.serverUrl + '/img/upload',
      filePath: file.url,
      name: 'file',
      success(res) {
        // 上传完成需要更新 fileList
        let json = JSON.parse(res.data)
        let fileName = json.data.fileName
        console.log(fileName)
        fileList.push({
          url: re.serverUrl + '/img/' + fileName,
          name: fileName
        })
        thisPtr.setData({ fileList })
      },
    });
  },
  delImg(e) {
    let index = e.detail.index
    let fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList
    })
  },

  // 更新申请分数
  onChangeStepper(e) {
    this.setData({ score: e.detail });
  },

  onSubmit() {
    const images = this.data.fileList.map(item => item.name)
    const imagesJson = JSON.stringify(images)

    const info = JSON.parse(wx.getStorageSync('userInfo'))

    const data = {
      studentId: info['id'],
      crpItemId: this.data.info.id,
      score: this.data.score,
      reason: this.data.reason,
      images: imagesJson,
    }

    re.postRequest("/score-record/apply", data).then(res => {
      // 展示成功
      wx.showToast({
        title: '成功',
        icon: 'success',
        duration: 2000
      })

      setTimeout(() => {
        // 切换页面
        wx.switchTab({
          url: "/pages/apply/apply"
        })
      }, 2000)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    re.getRequest(`/crp-item/${options.id}`).then(res => {
      let data = res.data
      this.setData({
        info: data
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})